<?php

namespace Lib\Model;

class CategoryModel {
       
    static function getAll() {
        $cache = \Lib\Registry::get('cache');
        $key = "categories_all";
        $categories = $cache->load($key, 120);
        if (!$categories) {
            $b = \Lib\Database::getConnection()->prepare("
            select *
            from category");
            $b->execute();
            $categories = $b->fetchAll(\PDO::FETCH_ASSOC);
            $cache->save($categories, $key);
        }
        return $categories;
    }
    
    static function getNotEmpty() {
        $cache = \Lib\Registry::get('cache');
        $key = "categories_not_empty";
        $categories = $cache->load($key, 120);
        if (!$categories) {
            $b = \Lib\Database::getConnection()->prepare("
            select c.*
            from category c
            join post p on p.category_id = c.id
            group by c.id
            having count(p.id) > 0");
            $b->execute();
            $categories = $b->fetchAll(\PDO::FETCH_ASSOC);
            $cache->save($categories, $key);
        }
        return $categories;
    }
    
    static function getByName($name) {
        $cache = \Lib\Registry::get('cache');
        $key = "category_" . $name;
        $category = $cache->load($key, 120);
        if (!$category) {
            $b = \Lib\Database::getConnection()->prepare("
            select *
            from category
            where name_en = :name");
            $b->bindValue("name", $name, \PDO::PARAM_STR);
            $b->execute();
            $category = $b->fetch(\PDO::FETCH_ASSOC);
            $cache->save($category, $key);
        }
        return $category;
    }
}

?>
